<?php
namespace admin\controllers;
use admin\models\AdminLoginForm;
use common\component\BaseWebController;
use common\models\VerifyCode;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

/**
 * Site controller
 */
class SiteController extends BaseWebController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(
            parent::behaviors(), [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'Captcha', 'forget', 'error', 'test'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'Captcha', 'index', 'test'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ]);
    }

    /**
     * Displays homepage.
     * @return mixed
     */
    public $title = 'XXX后台管理系统';

    public function actions(){
        return [
            'Captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'maxLength' => 4, //生成的验证码最大长度
                'minLength' => 4  //生成的验证码最短长度
            ],
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    //首页
    public function actionIndex()
    {
        $this->layout = 'mini';
        //定义title
        $this->getView()->title = "XXX后台管理系统";
        return $this->render('index');
    }

    //验证码验证
    public function actionCheck_code()
    {
        $verify = new VerifyCode();
        $verify->verifyCode = $_POST['verifyCode'];

        if($verify->validate()){
            echo json_encode([
                'code'=>200,
                'message'=>'验证通过',
            ]);
        }else{
            echo json_encode([
                'code'=>2001,
                'message'=>'验证码不一致',
            ]);
        }
    }

    //登录页
    public function actionLogin()
    {
        $this->layout = 'login_main';
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $post = $this->post();
        $model = new AdminLoginForm();
        if($model->load($post) && $model->login())
        {
            return $this->goBack();
        }else{
            Yii::$app->session->setFlash('error',$model->getFirstErrors());
        }

        //定义title
        $this->getView()->title = "登录";

        return $this->render('login', [
            'model'=>$model,
            'post'=>$post['LoginForm'],
        ]);
    }

    //登出
    public function actionLogout()
    {
        Yii::$app->user->logout();
        return $this->goHome();
    }

    //忘记密码页
    public function actionForget()
    {
        //定义title
        $this->layout = 'login_main';
        $this->getView()->title = "忘记密码";
        return $this->render('forget');
    }


}
